#include "Game.h"
#include "Xors3D.h"
#include <sstream>
using namespace std;


Game::Game( int width, int height, int depth )
{
	xGraphics3D(width, height, depth);
	xSetBuffer(xBackBuffer());

	InitScene();
	CreateCharacters();
}

Game::~Game()
{

}

void Game::InitScene()
{
	mLight = xCreateLight();
	xTurnEntity(mLight, 45,45,45);

	mPlane = xCreatePoly(4);
	xEntityColor(mPlane, 20, 20, 20);
	xMoveEntity(mPlane, 0, -2, 0);
	xScaleEntity(mPlane, 100,100,100);
	xRotateEntity(mPlane, 90,0,0);
	xEntityPickMode(mPlane,PICK_TRIMESH);

	mCamera = xCreateCamera();
}

void Game::CreateCharacters()
{
	//create player with speed of 0.5 and GREEN color
	mCharManager.CreatePlayer(mCamera, 0.5f, Color(0,255,0));

	for(int i = 0; i < 10; ++i)
	{
		mCharManager.CreateBot();
		mCharManager.CreateAngryBot();
	}
}

void Game::Update()
{
	UpdatePlayer();
	UpdateBots();
}

void Game::Run()
{
	while (!xKeyHit(KEY_ESCAPE))
	{

		xRenderWorld();
		Update();
		xFlip();
	}
}

void Game::UpdatePlayer()
{
	static bool needToMove = false;
	static Character* target = 0;

	Player *player = mCharManager.GetPlayer();

	if (xMouseHit(MOUSE_LEFT))
	{
		xCameraPick(mCamera, xMouseX(), xMouseY());
		if (xPickedEntity() == mPlane)
		{
			player->SetDestination(Vec3D(xPickedX(), 0, xPickedZ()));
			target = 0;
		}
		else
		{
			target = mCharManager.FindCharacter(xPickedEntity());			
		}
	}

	if (target)
	{
		if(!player->InPosition(target->GetPosition()))
		{
			player->SetDestination(target->GetPosition());
		}
		else
		{
			player->DealDamage(target);
			if (target->Attributes().Health() == 0)
			{
				target = 0;
			}
		}
	}
	player->Update();
	player->Move();

	stringstream stream;
	stream << string("Player HP: ") << player->Attributes().Health();
	xText(10,20, stream.str().c_str());

	if (target)
	{
		stream.str(string(""));
		stream.clear();
		stream << string("Target HP: ") << target->Attributes().Health();
		xText(10,30, stream.str().c_str());
	}
}

void Game::UpdateBots()
{
	vector<Bot*> bots = mCharManager.GetBots();
	for(size_t i = 0; i < bots.size(); ++i)
	{
		bots[i]->Update();
	}
}
